package ;
import com.funkyfurrymonkey.load.AssetsRepository;
import com.funkyfurrymonkey.load.ImageLoader;
import com.funkyfurrymonkey.load.DataLoader;
import com.funkyfurrymonkey.load.Preloader;
import com.funkyfurrymonkey.engine.Shuffle;
import deck.Card;
import deck.Deck;
import openfl.display.Bitmap;
import openfl.display.Sprite;

/**
 * ...
 * @author Marcos Martinez
 */
class Memory extends Sprite
{
	private var m_aAssetsRepository:AssetsRepository;
	private var m_cPreloader:Preloader ;
	private var m_cDeck:Deck ;
	public function new() 
	{
		super();
		m_aAssetsRepository = new AssetsRepository();
		
	}
	
	public function startLoading():Void
	{
		m_cPreloader = new Preloader(this, m_aAssetsRepository);
		m_cPreloader.start();
		m_cPreloader.onComplete = mainGame;
	}
	
	private function mainGame():Void
	{
		trace("main game");
		
		m_cDeck = new Deck(m_aAssetsRepository.getImage("cards"));
		m_cDeck.createCards();
		
		this.removeChild(m_cPreloader);
		//this.addChild(cDeck.m_aCards[Deck.DIAMONDS][12]);
		createGame();
	
		
	}
	
	private function createGame():Void
	{
		var aRandomPairs:Array<Int> = Shuffle.createArray(6, 52);
		aRandomPairs = aRandomPairs.concat(aRandomPairs);
		aRandomPairs = Shuffle.randomArray(aRandomPairs);
		trace("shuffle : " + aRandomPairs);
		//this.addChild(cDeck.m_bmRear);
		createDisplay(aRandomPairs);
	}
	
	private function createDisplay(aRandomPairs:Array<Int>):Void
	{
		var nCnt:Int = 0;
		for (card in aRandomPairs)
		{
			var cCard:Card = getCardFromNumber(card);
			cCard.x = nCnt * 80;
			nCnt++;
			trace("card :" + card + " x:" + cCard.x);
			this.addChild(cCard);
		}
		
	}
	
	private function getCardFromNumber(nId:Int):Card
	{
		var nNum:Int = nId % 13;
		var nShape:Int = Math.floor(nId / 13);
		trace("nid : " + nId + " shape :" + nShape+" num :" + nNum);
		return   m_cDeck.m_aCards[nShape][nNum];
	}
}